<?php

namespace App\Models\Api;

use App\Exceptions\ApiException;
use App\Models\Api\Base;
use AstroTool\Cache\CacheManage;
use Cache;


/**
 * 占卜模型类
 * Class Divination
 * @package 
 */
class Divination extends Base
{
    /**
     * 占卜所有的ids
     */
    const REDIS_KEY_IDS = 'divination_ids_';
    /**
     * 占卜详情
     */
    const REDIS_KEY_DETAIL = 'divination_detail_';

    protected $table = 'divination'; // 定义表名

    /**
     * 分页获取列表
     * @param array $map
     * @return array
     */
    public function getListPage($map = [])
    {
        //获取 用户所有占卜的id
        $divination_ids = false;
        if ($this->cache_on >= 1 && Cache::has(self::REDIS_KEY_IDS . $map['uid'])) {
            $divination_ids = Cache::get(self::REDIS_KEY_IDS . $map['uid']);
        }
        if ($divination_ids === false) {
            try {
                $divination_ids = $this
                    ->select('id')
                    ->where('uid', $map['uid'])
                    ->orderBy('id', 'DESC')
                    ->get();
            } catch (\Exception $e) {
                // 错误信息写入日志
                \Log::info('获取用户占卜ids错误:' . '[' . $map['rid'] . ']');
            }
            //获取数据
            $divination_ids = json_decode(json_encode($divination_ids, true), true);

            //存储所有ids
            if ($this->cache_on >= 1) {
                Cache::set(self::REDIS_KEY_IDS . $map['uid'], $divination_ids, $this->cache_time);
            }
        }

        if ($map['page'] == -1) { //获取所有
            $result = $divination_ids;
        } else { //分页获取
            //进行分页返回数据
            $total = count($divination_ids); //统计有多少个id
            $data_list = getPaginatorData($total, $map['page']); //获取数据分页信息
            $result = array_slice($divination_ids, $data_list['start'], $data_list['per_page']); //获取分页后的id数组
            unset($data_list['start']);
            unset($data_list['end']);
        }

        $result = array_column($result, 'id');
        $data_list['data'] = $this->getDetails($result);

        return $data_list;
    }

    /**
     * 查询单个占卜的详情
     * @param array $map
     * @param array $fields
     * @return array|bool|mixed
     * @throws \Exception
     */
    // public function getDetail($map = [], $fields = [])
    // {
    //     $datas = $this->getDetailsByIds([$map['id']], $fields);

    //     $data = current($datas);

    //     if (!$data) {
    //         throw new ApiException('数据不存在', 200, config('code.error'));
    //     }

    //     return $data;
    // }
    
      /**
     * 查询单个占卜的详情
     * @param array $map
     * @return array|bool|mixed
     */
    public function getDetail($map = [])
    {
        $data = false;

        // if ($this->cache_on >= 1)
        // {
        //     $data = Cache::get(self::REDIS_KEY_DETAIL . $map['id']);
        // }

        if ($data === false)
        {
            try
            {
                $where['id'] = intval($map['id']);

                $data = $this->select(['id','question','planet','sign','house','deg','timezone','create_time','longitude','latitude','tag_id'])
                    ->where($map)->first()->toArray();
            }
            catch (\Exception $e)
            {
                $this->error = '数据不存在';
                return false;
            }
        }

        return $data;
    }


    /**
     * 通过ID批量获取占卜详情
     * @param array $ids
     * @param array $fields
     * @return array
     * @throws \Exception
     */
    public function getDetailsByIds(array $ids, $fields = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig('divination')
            ->batchGetCache($ids, function ($ids) {
                return $this->getDataByIds($ids);
            }, $fields, 'list_details');
        return $data;
    }

    /**
     * 通过ID 批量获取占卜详情
     * @param array $ids
     * @return array
     * @throws ApiException
     */
    protected function getDataByIds(array $ids)
    {
        try {
            $data = $this->whereIn('id', $ids)->get(['id', 'uid', 'question', 'planet', 'sign', 'house', 'deg', 'timezone', 'create_time', 'longitude', 'latitude', 'tag_id'])->keyBy('id')->toArray();
            //var_dump($data);die;
        } catch (Exception $e) {
            \Log::info('获取占卜详情错误:' . $e->getMessage() . date('Y-m-d H:i:s'));
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $data;
    }

    /**
     * 获取所有的详情
     * @param array $all_list
     * @return array
     * @throws \Exception
     */
    public function getDetails($all_list = [])
    {
        $result = [];

        $data = $this->getDetailsByIds($all_list, $fields = []);

        // 循环重组数据
        foreach ($all_list as $v) {
            if (isset($data[$v])) {
                $result[] = $data[$v];
            }
        }

        return $result;
    }
}
